<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\Admin\PermissionDeniedException;
use App\Interfaces\CategoryService;
use App\Interfaces\SolrService;
use App\Models\Category;
use App\Models\Goods;
use App\Models\GoodsEorderInfo;
use App\Models\GoodsGallery;
use App\Models\GoodsStockHistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AdminCategory\CategoryRequest;
use App\Http\Requests\Admin\Goods\GoodsEorderInfoRequest;
use App\Models\Brand;
use App\Models\Activity;
use App\Models\ActivityGoods;
use App\Models\ActivityCat;
use App\Models\SearchKeywords;
use App\Models\RecommendPosition;
use App\Models\Recommend;
use App\Interfaces\GoodsService;
use App\Models\CategoryBrand;
use App\Models\GoodsContent;
use App\Models\Shop;
use Illuminate\Support\Facades\Session;
use Gate;
use App\Models\Warehouse;
use Auth,Log;

use App\Commands\OperationLogCommand;
use App\Http\Requests\Admin\AdminGoods\GoodsStockOpreationRequest;
use App\Interfaces\StockService;
use App\Interfaces\GoodsStockHistoryService;
use App\Http\Requests\Admin\AdminGoods\GoodsCreateRequest;
use App\Http\Requests\Admin\AdminGoods\GoodsUpdateRequest;
use App\Models\ProductSku;
use DB, Excel;

use App\Exceptions\Interfaces\StockServiceException;

class GoodsController extends Controller
{
    private $fir_num=0;

    private $sec_num=0;

    private $goods = [];

    public function goods_gate(){

        if (!Gate::allows('goods','')) {
            throw new PermissionDeniedException();
        }//end if()
    }//end func order_query()


    public function goods_edit_gate(){

        if (!Gate::allows('goods_edit','')) {
            throw new PermissionDeniedException();
        }//end if()
    }//end func order_query()

    public function index(Request $request, Category $category){

        $this->goods_gate();

    	//品牌数组
    	$brandInfo = Brand::all();
    	$brandArr = ['0'=>'选择品牌'];
    	foreach ($brandInfo as $key => $value) {
    		$brandArr[$value->brand_id] = $value->brand_name;
    	}//end foreach()

    	//分类数组
    	/*$categoryArr = ['0'=>'所有分类'];
    	$categoryInfo = Category::get();
    	foreach ($categoryInfo as $key => $value) {
    		$categoryArr[$value->cat_id] = $value->cat_name;
    	}//end foreach()*/


    	//是否上下架
        $isOnSaleArr = ['0'=>'所有上下架', '1'=>'上架', '2'=>'下架'];
        $auditStatusArr = ['All'=>'所有审核状态','0'=>'未审核','1'=>'审核通过','2'=>'审核不通过'];
        $typeArr = ['-1'=>'选择类型', '0'=>'一般商品', '1'=>'e贸易商品'];
        $goodsNumberArr = ['All'=>'库存','0-50'=>'0-50','50-100'=>'50-100','100-200'=>'100-200','200-500'=>'200-500','500-'=>'500以上'];



        $search = array('cat_id'=>0, 'brand_id'=>0, 'type'=>-1, 'is_on_sale'=>0,'audit_status'=>'All','goods_number'=>'All', 'goods_name'=>'', 'goods_sn'=>'');
        $query =  Goods::orderBy('sort_order','desc')->orderBy('add_time', 'desc')->orderBy('goods_id', 'desc');

        if ($request->get('cat_id')!='' && $request->get('cat_id')!=0){
            $query = $query->where('cat_id', $request->get('cat_id'));
            $search['cat_id'] = $request->cat_id;
        }//end if()

        if ($request->get('brand_id')!='' && $request->get('brand_id')!=0){
            $query = $query->where('brand_id', $request->get('brand_id'));
            $search['brand_id'] = $request->brand_id;
        }//end if()

        if ($request->get('type')!='' && $request->get('type')!=-1){
            $query = $query->where('type', $request->get('type'));
            $search['type'] = $request->type;
        }//end if()

        if (!empty($request->get('goods_name'))){
            $goods_name = $request->goods_name;
            $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);

            $query = $query->where('goods_name', 'like', "%".trim($goods_name)."%");
            $search['goods_name'] = $request->goods_name;
        }//end if()

        if (!empty($request->get('goods_sn'))){
            $goods_sn = $request->goods_sn;
            $goods_sn = preg_replace('~\s{2,}~', ' ', $goods_sn);
            $query = $query->where('goods_sn', 'like', "%".$goods_sn."%");
            $search['goods_sn'] = $request->goods_sn;
        }//end if()

        if ($request->get('audit_status')!='' && $request->get('audit_status')!="All"){
            $query = $query->where('audit_status', $request->get('audit_status'));
            $search['audit_status'] = $request->audit_status;
        }//end if()

        if ($request->get('is_on_sale')!='' && $request->get('is_on_sale')!=0){
            $query = $query->where('is_on_sale', $request->get('is_on_sale'));
            $search['is_on_sale'] = $request->is_on_sale;
        }//end if()

        if ($request->get('goods_number')!='' && $request->get('goods_number')!='All'){
            $goods_number = explode('-',$request->get('goods_number'));
            if($goods_number[1]){
                $query = $query->where('goods_number','>=',$goods_number[0]);
                $query = $query->where('goods_number','<=',$goods_number[1]);

            }else{
                $query = $query->where('goods_number','>=',$goods_number[0]);
            }
            $search['goods_number'] = $request->goods_number;
        }//end if()

        $goods = $query->paginate(10);

        foreach ($goods as $key => $value) {
        	$cat_id = $value->cat_id;

        	$categorys = Category::where('cat_id', $cat_id)->get();

        	$goods[$key]['cat_name'] = @$categorys[0]->cat_name;
        }//end foreach()


        //活动数组
        $activityArr = ['0'=>'请选择活动'];
        $activityInfo = Activity::get();
        foreach ($activityInfo as $key => $value) {
            $activityArr[$value->id] = $value->name;
        }//end foreach()

        //推荐位置数组
        $recommendArr = ['0'=>'请选择推荐位置'];
        $recommendInfo = RecommendPosition::get();
        foreach ($recommendInfo as $key => $value) {
            $recommendArr[$value->id] = $value->name;
        }//end foreach()

        return view('admin.goods.index',compact(['goods','category', 'brandArr', 'typeArr','auditStatusArr', 'isOnSaleArr', 'activityArr', 'recommendArr','goodsNumberArr','search']));

    }//end func index()

    public function create(Goods $goods,Category $category){

        $this->goods_gate();

        //品牌数组
    	$brandInfo = Brand::all();
    	$brandArr = ['0'=>'=请选择品牌='];

        //店铺数组
        $shopInfo = Shop::all();
        $shopArr = ['0'=>'=选择店铺='];
        foreach ($shopInfo as $key => $value) {
            $shopArr[$value->id] = $value->shop_name;
        }//end foreach()

        $typeArr = ['0'=>'一般商品', '1'=>'e贸易商品'];

        return view('admin.goods.create',compact(['goods','category', 'brandArr', 'shopArr', 'typeArr']));
    }


	/**
	 * 添加商品
	 *
	 *
	 * @date 2015/12/09
	 * @author Leen
	 */
    public function store(GoodsCreateRequest $goodsRequest,CategoryService $categoryService,GoodsEorderInfo $goodsEorderInfo ,StockService $stockService, GoodsStockHistoryService $goodsStockHistoryService)
    {

        $this->goods_gate();

        $requestParam = $goodsRequest->all();
        $goods_sn = $goodsRequest->get('goods_sn');
        $type = $goodsRequest->get('type');

        $goods_name = $goodsRequest->goods_name;
        $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);       //将商品名字中间多个空格替换为一个空格
        $requestParam['goods_name'] = $goods_name;

        $goodsArr = Goods::lists('goods_sn')->toArray();
        $is_goods = in_array($goods_sn,$goodsArr);
        if($is_goods){
            return redirect::back()->withInput()->with('message','该货号已存在');
        }

        if($type==1){
            $egoodsArr = GoodsEorderInfo::lists('goods_sn')->toArray();
            //dd($egoodsArr);
            $is_goods_sn = in_array($goods_sn,$egoodsArr);
            //dd($egoodsArr);
            if($is_goods_sn){
                $goods = Goods::create($requestParam);
            }else{
                return redirect::back()->withInput()->with('message','该货号未备案');
                //return redirect::back()->withError()->with('message','该货号不存在');
            }
        }else{
            $goods = Goods::create($requestParam);
        }


        $this->dispatch(
            new OperationLogCommand('添加商品', 'Goods','goods_id:'.$goods->goods_id)
        );


        if ($goods){
            $requestParam['goods_id'] = $goods->goods_id;

            $goods_id = $goods->goods_id;
            $goods_sn = $goods->goods_sn;
            $goods_name = $goods->goods_name;
            $cat_id = $goods->cat_id;
            $brand_id = $goods->brand_id;
            $keywords = $goods->keywords;
            $goods_number = $goods->goods_number;

            if(!empty($goods_number) && $goods_number>0){

                $user_id = Auth::user()->id;
                $operation = 1;
                $describe = '添加商品时增加库存，数量：'.$goods_number;

                //$stockService->updateStock($goods_sn, $user_id, $goods_number, $operation, $describe, $goodsStockHistoryService);
                $goodsStockHistoryService->updateStockHistory($goods_id, $user_id, $describe, $goods_number, $operation);
            }


            $goods_content = @$goodsRequest->goods_content;
            $mobile_goods_content = @$goodsRequest->mobile_goods_content;
            if(!empty($goods_content)){
                $goodsContent = GoodsContent::find($goods_id);

                if($goodsContent){
                    //update
                    $goodsContents = GoodsContent::where('goods_id', $goods_id)->update(['goods_content'=>$goods_content, 'mobile_goods_content'=>$mobile_goods_content]);
                }else{
                    //insert
                    $goodsContents = GoodsContent::insert(['goods_id' => $goods_id, 'goods_content' => $goods_content, 'mobile_goods_content'=>$mobile_goods_content]);
                }//end if()
            }//end if()

            //创建商品相册
            $requestGallery = $goodsRequest->get('goods_gallery');
            $requestGallery['goods_id'] = $goods_id;
            GoodsGallery::create($requestGallery);


            $category = Category::find($cat_id);
            if(!count($category)){
                $cat_id = 0;
            }//end if()

            $brand = Brand::find($brand_id);
            if(!count($brand)){
                $brand_id = 0;
            }//end if()

            if(!empty($keywords)){
                $keywords = preg_replace("/((\n)|(\s)|(\t)|(，))/", ',', $keywords);
                $keywords = trim($keywords, ',');
                $keywordsStr = trim($keywords);
            }else{
                $keywordsStr = '';
            }//end if()
            $this->keywords($goods_id, $keywordsStr, $cat_id, $brand_id,$categoryService);





        }//end if()



        return Redirect('admin/goods');

    }//end func store()


    /**
     * 获取商品
     *
     * @date 2016/04/19
     * @author Leen
     */
    public function show($id, Request $request, Category $category)
    {


        //品牌数组
        $brandInfo = Brand::all();
        $brandArr = ['0'=>'选择品牌'];
        foreach ($brandInfo as $key => $value) {
            $brandArr[$value->brand_id] = $value->brand_name;
        }//end foreach()

        //是否上下架
        $isOnSaleArr = ['0'=>'所有上下架', '1'=>'上架', '2'=>'下架'];
        $auditStatusArr = ['All'=>'所有审核状态','0'=>'未审核','1'=>'审核通过','2'=>'审核不通过'];
        $typeArr = ['-1'=>'选择类型', '0'=>'一般商品', '1'=>'e贸易商品'];
        $goodsNumberArr = ['All'=>'库存','0-50'=>'0-50','50-100'=>'50-100','100-200'=>'100-200','200-500'=>'200-500','500-'=>'500以上'];

        $search = array('cat_id'=>0, 'brand_id'=>0, 'type'=>0, 'is_on_sale'=>0,'audit_status'=>'All','goods_number'=>'All', 'goods_name'=>'', 'goods_sn'=>'');

        $query =  Goods::orderBy('sort_order','desc')->orderBy('add_time', 'desc')->orderBy('goods_id', 'desc');

        if ($request->get('cat_id')!='' && $request->get('cat_id')!=0){
            $query = $query->where('cat_id', $request->get('cat_id'));
            $search['cat_id'] = $request->cat_id;
        }//end if()

        if ($request->get('brand_id')!='' && $request->get('brand_id')!=0){
            $query = $query->where('brand_id', $request->get('brand_id'));
            $search['brand_id'] = $request->brand_id;
        }//end if()

        if ($request->get('type')!='' && $request->get('type')!=-1){
            $query = $query->where('type', $request->get('type'));
            $search['type'] = $request->type;
        }//end if()

        if (!empty($request->get('goods_name'))){
            $goods_name = $request->goods_name;
            $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);

            $query = $query->where('goods_name', 'like', "%".trim($goods_name)."%");
            $search['goods_name'] = $request->goods_name;
        }//end if()

        if (!empty($request->get('goods_sn'))){
            $goods_sn = $request->goods_sn;
            $goods_sn = preg_replace('~\s{2,}~', ' ', $goods_sn);
            $query = $query->where('goods_sn', 'like', "%".$goods_sn."%");
            $search['goods_sn'] = $request->goods_sn;
        }//end if()

        if ($request->get('audit_status')!='' && $request->get('audit_status')!="All"){
            $query = $query->where('audit_status', $request->get('audit_status'));
            $search['audit_status'] = $request->audit_status;
        }//end if()

        if ($request->get('is_on_sale')!='' && $request->get('is_on_sale')!=0){
            $query = $query->where('is_on_sale', $request->get('is_on_sale'));
            $search['is_on_sale'] = $request->is_on_sale;
        }//end if()

        if ($request->get('goods_number')!='' && $request->get('goods_number')!='All'){
            $goods_number = explode('-',$request->get('goods_number'));
            if($goods_number[1]){
                $query = $query->where('goods_number','>=',$goods_number[0]);
                $query = $query->where('goods_number','<=',$goods_number[1]);

            }else{
                $query = $query->where('goods_number','>=',$goods_number[0]);
            }
            $search['goods_number'] = $request->goods_number;
        }//end if()

        $goods = $query->paginate(10);

        foreach ($goods as $key => $value) {
            $cat_id = $value->cat_id;

            $categorys = Category::where('cat_id', $cat_id)->get();

            $goods[$key]['cat_name'] = @$categorys[0]->cat_name;
        }//end foreach()
        return $goods;
    }//end func show


    /**
     * 添加商品搜索关键词
     *
     *
     * @date 2015/12/09
     * @author Leen
     */
    public function keywords($goods_id, $keywordsStr, $cat_id, $brand_id,$categoryService)
    {

        $this->goods_gate();

        if(empty($goods_id)){
            return false;
        }//end if()

        $brand = Brand::find($brand_id);

        if ($brand){
            $keywordsStr.=','.$brand->brand_name;
        }

        $path = $categoryService->getPath($cat_id);

        foreach ($path as $category){
            if ($category) $keywordsStr.=','.$category->cat_name.','.$category->keywords;
        }
        $goods = Goods::find($goods_id);

        $goods->search_keywords = $keywordsStr;

        $goods->save();
//        $this->dispatch(
//            new OperationLogCommand('添加了商品[goods_id:'.$goods->goods_id.', goods_name'.$goods->goods_name.']搜索关键词[search_keywords:'.$goods->search_keywords.']')
//        );

    }//end func keywords


    /**
     * 根据商品删除商品的搜索关键词
     *
     *
     * @date 2015/12/26
     * @author Leen
     */
    public function delKeywords($goods_id)
    {
        SearchKeywords::where('goods_id', $goods_id)->delete();

    }//end func delKeywords


	/**
	 * 编辑商品
	 *
	 * param
	 *
	 * @date 2015/12/12
	 * @author Leen
	 */
    public function edit($goods_id,Category $category, Request $request)
    {

        $this->goods_edit_gate();

        $back_url = '';
        if($request->back_url){
            $back_url = $request->back_url;
        }

        $goods = Goods::findOrNew($goods_id);


        if(!empty($goods)){
            $goods_id = $goods->goods_id;
            $goodsContent = GoodsContent::find($goods_id);

            if($goodsContent){

                $goods_content = $goodsContent->goods_content;
                $mobile_goods_content = $goodsContent->mobile_goods_content;
            }else{

                $goods_content = '';
                $mobile_goods_content = '';
            }//end if()
            $goods['goods_content']=$goods_content;
            $goods['mobile_goods_content']=$mobile_goods_content;

            // $goodsGallery = GoodsGallery::findOrNew($goods->goods_id);
            $goodsGallery = GoodsGallery::find($goods->goods_id);

            $cat_id = $goods->cat_id;
            $categoryBrand = CategoryBrand::where('cat_id', $cat_id)->get();

            //$brandInfo = Brand::all();
            $brandArr = ['0'=>'=请选择品牌='];
            foreach ($categoryBrand as $key => $value) {
                $brand_id = $value->brand_id;
                $brand_name = Brand::find($brand_id)->brand_name;

                $brandArr[$brand_id] = $brand_name;
            }//end foreach()

            //店铺数组
            $shopInfo = Shop::all();
            $shopArr = ['0'=>'=选择店铺='];
            foreach ($shopInfo as $key => $value) {
                $shopArr[$value->id] = $value->shop_name;
            }//end foreach()

            $typeArr = ['0'=>'一般商品', '1'=>'e贸易商品'];

            return view('admin.goods.edit', compact(['goods','goodsEorderInfo','category', 'brandArr','goodsGallery','shopArr','typeArr', 'back_url']));

        }//end if()

    }//end func store()


	/**
	 * 编辑更新商品
	 *
	 *
	 * @date 2015/12/10
	 * @author Leen
	 */
    public function update($id, GoodsUpdateRequest $goodsRequest,SolrService $solrService,CategoryService $categoryService)
    {

        $this->goods_gate();

        //验证带E贸易请求
        if ($goodsRequest->type){
            new GoodsEorderInfoRequest();
        }
        $goodsInfo = Goods::find($id);

        if ($goodsInfo) {

            $goods_name = $goodsRequest->goods_name;
            $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);       //将商品名字中间多个空格替换为一个空格
            $goodsRequest['goods_name'] = $goods_name;

            //更新主表
            $goodsInfo->update($goodsRequest->all());
            $this->dispatch(
                new OperationLogCommand('修改商品','Goods','goods_id:'.$id)
            );
            $goodsInfo->audit_status=0;
            $goodsInfo->is_on_sale=2;
            $goodsInfo->save();



            //更新goods_content
            $goods_id = $goodsInfo->goods_id;
            $cat_id = $goodsInfo->cat_id;
            $brand_id = $goodsInfo->brand_id;
            $keywords = $goodsInfo->keywords;

            $goods_content = @$goodsRequest->goods_content;
            $mobile_goods_content = @$goodsRequest->mobile_goods_content;


                $goodsContent = GoodsContent::find($goods_id);

            if($goodsContent){

                $goodsContents = GoodsContent::where('goods_id', $goods_id)->update(['goods_content'=>$goods_content, 'mobile_goods_content'=>$mobile_goods_content]);
            }else{

                $goodsContents = GoodsContent::insert(['goods_id' => $goods_id, 'goods_content' => $goods_content, 'mobile_goods_content'=>$mobile_goods_content]);
            }//end if()



            //更新相册
            if ($goods_id){

                // DB::connection()->enableQueryLog(); // 开启查询日志

                $goodsGallery=GoodsGallery::find($goods_id);

                if ($goodsGallery) {

                    $goodsGallery->update($goodsRequest->get('goods_gallery'));
                }else{

                    //创建商品相册
                    $requestGallery = $goodsRequest->get('goods_gallery');

                    $requestGallery['goods_id'] = $goods_id;

                    GoodsGallery::create($requestGallery);
                }

                /*$queries = DB::getQueryLog(); // 获取查询日志
                dd($queries);*/
    //            $this->dispatch(
    //                new OperationLogCommand('更新商品相册[goods_id:'.$goods_id.']')
    //            );

            }//end if()

            $category = Category::find($cat_id);
            if(!count($category)){
                $cat_id = 0;
            }//end if()

            $brand = Brand::find($brand_id);
            if(!count($brand)){
                $brand_id = 0;
            }//end if()

            if(!empty($keywords)){

                $keywords = preg_replace("/((\n)|(\s)|(\t)|(，))/", ',', $keywords);
                $keywords = trim($keywords, ',');

                $keywordsStr = trim($keywords);
            }else{

                $keywordsStr = '';
            }//end if()

            $this->keywords($goods_id, $keywordsStr, $cat_id, $brand_id,$categoryService);

            //SOLR同步数据
            $solrService->update($goodsInfo);
        }

        $pre_url = @$goodsRequest->pre_url;

        if($pre_url){

            return Redirect($pre_url);
        }else{

            return Redirect('admin/goods/');
        }

    }//end func store()

	/**
	 * 编辑更新商品
	 *
	 *
	 * @date 2015/12/10
	 * @author Leen
	 */
    public function updateOne($id, Request $request,SolrService $solrService)
    {

        $this->goods_gate();


        $goods = Goods::find($id);

        if ($goods->is_on_sale==1){

        	$goods->is_on_sale=2;
            $solrService->delete($id);
        }else{

        	$goods->is_on_sale=1;
            $solrService->update($goods);
        }

        $goods->save();
        $this->dispatch(
            new OperationLogCommand('切换商品上下架','Goods','goods_id:'.$id)
        );

		$return['is_on_sale']=$goods->is_on_sale;


        return Response()->json($return);


    }//end func store()

    /**
     * 编辑更新商品是否首页推荐,是否分类推荐
     *
     *
     * @date 2015/12/17
     * @author Leen
     */
    public function updateTwo($id, $name)
    {

        $this->goods_gate();

        $goods = Goods::find($id);

        if ($goods->$name==1){

            $goods->$name=0;

        }else{

            $goods->$name=1;

        }

        $goods->save();

        $return[$name]=$goods->$name;


        return Response()->json($return);


    }//end func store()


	/**
	 * 删除商品
	 *
	 *
	 * @date 2015/12/12
	 * @author Leen
	 */
    public function destroy($id,SolrService $solrService)
    {

        $this->goods_gate();

        DB::beginTransaction();
        try {

        $goodsInfo = Goods::find($id);

        $goodsInfo->delete();
        $this->dispatch(
            new OperationLogCommand('删除商品','Goods','goods_id:'.$id)
        );
        $this->delKeywords($id);

        ActivityGoods::where('goods_id', $id)->delete();
        GoodsStockHistory::where('goods_id', $id)->delete();

        $solrService->delete($goodsInfo->goods_id);
        ProductSku::where('goods_id', $id)->delete();

        } catch (Exception $e) {

            DB::rollback();
            throw new Exception("删除商品失败");

        }//end try
        DB::commit();

        return Redirect('admin/goods');

    }//end func store()

	/**
	 * 商品排序
	 *
	 *
	 * @date 2015/12/12
	 * @author Leen
	 */
    public function sort(Request $request){

        $this->goods_gate();

        foreach ($request->get('sort_order') as $id=>$v){

            Goods::find($id)->update(['sort_order'=>$v]);
        }
//        $this->dispatch(
//            new OperationLogCommand('执行了商品排序','排序','Goods表')
//        );
        return Redirect('admin/goods');

    }//end func sort()


    /**
     * 添加商品到活动
     *
     *
     * @date 2015/12/09
     * @author Leen
     */
    public function addGoodsToAct($cat_id, Request $request)
    {

        $this->goods_gate();

        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $goodsArr = $request->get('goodsArr');

        $goodsStr = "";
        for($i=0;$i<count($goodsArr);$i++){
            $goodsStr = $goodsStr.$goodsArr[$i]." ";
        }

        foreach ($goodsArr as $key => $value) {
            $goods_id = $value;

            $result = ActivityGoods::where('activity_cat_id', $cat_id)
                    ->where('goods_id', $goods_id)
                    ->get();
            $activityCat = ActivityCat::where('id',$cat_id)->get()->first();
            $activity_name = Activity::where('id',$activityCat->activity_id)->pluck('name');
            if(count($result)==0){
                ActivityGoods::insertGetId(['activity_cat_id' => trim($cat_id), 'goods_id' => $goods_id]);
            }else{
                /*$return['status'] = 0;
                $return['message'] = '该商品已经存在活动中';*/
            }//end if()

        }//end foreach()
//        $this->dispatch(
//            new OperationLogCommand('将商品[goods_id:'.$goodsStr.']添加到活动[id:'.$activityCat->activity_id.',name:'.$activity_name.']下的分类[activity_cat_id:'.$activityCat->id.',cat_name:'.$activityCat->cat_name.']')
//        );
        $this->dispatch(
            new OperationLogCommand('推荐商品','ActivityGoods','goods_id:'.$goodsStr.',activity_cat_id:'.$cat_id)
        );
        return Response()->json($return);

    }//end func addGoodsToAct()

    /**
     * 添加商品到推荐位置
     *
     *
     * @date 2015/12/19
     * @author Leen
     */
    public function addGoodsToRecommend($recommend_position_id, Request $request)
    {

        $this->goods_gate();

        $return = ['status'=>1, 'message'=>'', 'data'=>''];
        $relationArr = $request->get('relationArr');

        $goodsStr = "";
        for($i=0;$i<count($relationArr);$i++){
            $goodsStr = $goodsStr.$relationArr[$i]." ";
        }
        $recommendPosition = RecommendPosition::where('id',$recommend_position_id)->get()->first();

        foreach ($relationArr as $key => $value) {
            $relation_id = $value;

            $result = Recommend::where('recommend_position_id', $recommend_position_id)
                    ->where('relation_id', $relation_id)
                    ->get();
            if(count($result)==0){
                $goods = Goods::where('goods_id', $relation_id)->get();
                foreach ($goods as $key => $value) {
                    $goods_name = $value->goods_name;
                    $goods_thumb = $value->goods_thumb;
                    $goods_desc = $value->goods_desc;

                    Recommend::insertGetId(['recommend_position_id' => trim($recommend_position_id), 'relation_id' => trim($relation_id), 'title'=>"$goods_name", 'picture'=>"$goods_thumb", 'description'=>"$goods_desc", 'sort_order'=>0, 'link' => trim($relation_id)]);
                }//end foreach()

            }

        }//end foreach()
        $this->dispatch(
            new OperationLogCommand('推荐商品','Recommend','goods_id:'.$goodsStr.',recommend_position_id:'.$recommend_position_id)
        );
        return Response()->json($return);

    }//end func store()


    /**
     * 商品入库、出库
     *
     *
     * @date 2016/02/16
     * @author Leen
     */
    public function updateStock($goods_id, GoodsStockOpreationRequest $request, StockService $stockService, GoodsStockHistoryService $goodsStockHistoryService,SolrService $solrService)
    {

        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        $this->goods_gate();

        $goods_stock = $request->goods_stock;
        $operation = $request->operation;
        $user_id = Auth::user()->id;

        if($operation=='plus'){

            $describe = '增加库存，数量：'.$goods_stock;

        }elseif($operation=='reduce'){

            $describe = '减少库存，数量：'.$goods_stock;

        }//end if()

        try {

            $stockService->updateStock($goods_id, $user_id, $goods_stock, $operation, $describe, $goodsStockHistoryService);

        } catch (StockServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();

            return Response()->json($return);
        }

        //同步solr
        $goods = Goods::find($goods_id);
        $goods->stock=$goods_stock;
        $solrService->update($goods);


        $pre_url = @$request->pre_url;

        if($pre_url){

            $return['data'] = $pre_url;

            // return Redirect($pre_url);
        }else{

            $return['data'] = 'admin/goods';

            // return Redirect('admin/goods');
        }

        return Response()->json($return);
    }//end func store()

//修改审核状态
    public function toggleShow(Request $request,Goods $goods,SolrService $solrService){
        //dd($request->all());

        $this->goods_gate();

        $id = $request->id;
        $audit_status = $request->audit_status;
        $goods=Goods::find($id);
        //dd($audit_status!=1);
        if($audit_status!=1){
            //$goods->is_on_sale=2;
            $solrService->delete($id);
        }
        $goods->audit_status=$audit_status;
        $goods->save();
        $this->dispatch(
            new OperationLogCommand('修改商品审核状态', 'Goods','goods_id:'.$id)
        );

        return response()->json(['status'=>200]);

    }

    /**
     * [根据商品id判断商品是否存在]
     * @param  [type]  $goods_id [商品id]
     * @return boolean           [商品是否存在，存在返回true,不存在返回false]
     */
    public function isHasGoods($goods_id)
    {

        $this->goods_gate();

        $goods = Goods::find($goods_id);

        if ($goods) {

            return 'true';
        }else{

            return 'false';
        }//end if()
    }//end func isHasGoods


    /**
     * 批量入库
     * @param  string $path [批量excel表格路径]
     * @return [type]        [description]
     */
    public function batchStorage(Request $request, StockService $stockService, GoodsStockHistoryService $goodsStockHistoryService,SolrService $solrService)
    {

        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        Log::info('批量入库文件路径：');

        Log::info('request:'.json_encode($request->all()));

        if (! empty ( $_FILES ['file'] ['name'] ))
         {

            $tmp_file = $_FILES ['file'] ['tmp_name'];
            $file_types = explode ( ".", $_FILES ['file'] ['name'] );
            $file_type = $file_types [count ( $file_types ) - 1];

            /*判别是不是.xls文件，判别是不是excel文件*/
            if (strtolower ( $file_type ) != "xls" && strtolower ( $file_type ) != "xlsx" )
            {
                $return['status'] = 0;

                $return['message'] = '不是Excel文件，请重新选择上传';

                return Response()->json($return);
             }


            //读取excel内容
            Excel::load($tmp_file, function($reader) {

                $results = $reader->get()->toArray();

                foreach ($results as $key=>$val) {

                    // 进行数据操作
                    $goods_id = Goods::where('goods_sn', trim($val['goods_sn']))->pluck('goods_id');
                    $this->goods[$key]['goods_id'] = intval($goods_id);
                    $this->goods[$key]['goods_sn'] = $val['goods_sn'];
                    $this->goods[$key]['storage_num'] = intval($val['storage_num']);
                    $this->goods[$key]['operation'] = 1;      //库存操作状态：1，加库存；2：减库存；3，其他操作
                    $this->goods[$key]['describe'] = '批量增加库存，数量：'.$this->goods[$key]['storage_num'];
                    $this->goods[$key]['oper_type'] = 1;      //操作类型， 0:单个操作；1: 后台批量操作;

                }
            });

            if (count($this->goods)) {

                try {

                    $stockService->batchUpdateStock($this->goods, Auth::user()->id, $goodsStockHistoryService, $solrService);

                } catch (StockServiceException $e) {

                    /*$return['status'] = 0;

                    $return['message'] = $e->getMessage();

                    return Response()->json($return);*/

                    if($pre_url){

                        return Redirect($pre_url);
                    }else{

                        return Redirect('admin/goods');
                    }
                }
            }

        }

        $pre_url = @$request->pre_url;

        if($pre_url){

            // $return['data'] = $pre_url;

            return Redirect($pre_url);
        }else{

            // $return['data'] = 'admin/goods';

            return Redirect('admin/goods');
        }

        // return Response()->json($return);

        //第一步：读取excel表格中的商品货号及对应的入库数量

        //第二步：根据货号获取商品的id

        //第三步：将商品入库

    }

    /**
     * 批量出库
     * @param  string $goods [商品id和出库数量的数组]
     * @return [type]        [description]
     */
    public function batchOutGoing(Request $request, StockService $stockService, GoodsStockHistoryService $goodsStockHistoryService,SolrService $solrService)
    {

        $return = ['status'=>1, 'message'=>'出库成功', 'data'=>''];

        Log::info('批量出库:'.json_encode($request->goods));

        if (empty($request->goods) || count($request->goods)<1) {

            $return['status'] = 0;

            $return['message'] = '出库的商品不能为空';

            return Response()->json($return);
        }

        $goods = $request->goods;

        // $goods = [['id'=>966, 'number'=>1], ['id'=>967, 'number'=>2]];

        $out_going_goods = [];      //要批量更新的商品数组

        /*$export_goods = [];         //要导出excel的商品数组*/

        foreach ($goods as $key=>$good) {

            // 进行数据操作
            $goodObj = Goods::where('goods_id', trim($good['id']))->first();

            /*if ($goodObj) {

                $export_goods[$key] = $goodObj->toArray();
                $export_goods[$key]['out_going_number'] = $good['number'];
            }else{

                $export_goods[$key] = [];
            }*/

            $out_going_goods[$key]['goods_id'] = intval($good['id']);
            $out_going_goods[$key]['goods_sn'] = $goodObj['goods_sn'];
            $out_going_goods[$key]['storage_num'] = intval($good['number']);
            $out_going_goods[$key]['operation'] = 2;      //库存操作状态：1，加库存；2：减库存；3，其他操作
            $out_going_goods[$key]['describe'] = '批量减少库存，数量：'.intval($good['number']);
            $out_going_goods[$key]['oper_type'] = 1;      //操作类型， 0:单个操作；1: 后台批量操作;
        }

        try {

            $stockService->batchUpdateStock($out_going_goods, Auth::user()->id, $goodsStockHistoryService, $solrService);

            //导出excel
            /*$this->exportGoods($export_goods);*/

            $return['data'] = $out_going_goods;

        } catch (StockServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();

            return Response()->json($return);
        }

        return Response()->json($return);
    }

    /**
     * 导出出库商品的excel
     * @param  [type] $goods [商品数组]
     * @return [type]        [description]
     */
    public function exportGoods(Request $request)
    {

        $return = ['status'=>1, 'message'=>'导出成功', 'data'=>''];

        if (empty($request->goods) || count($request->goods)<1) {

            $return['status'] = 0;

            $return['message'] = '导出出库的商品不能为空';

            return Response()->json($return);
        }

        $goods = $request->goods;

        $date=date('Ymd');

        $export_goods = [];         //要导出excel的商品数组

        foreach ($goods as $key=>$good) {

            // 进行数据操作
            $goodObj = Goods::where('goods_id', trim($good['id']))->first();

            if ($goodObj) {

                $export_goods[$key] = $goodObj->toArray();
                $export_goods[$key]['out_going_number'] = $good['number'];
            }else{

                $export_goods[$key] = [];
            }
        }

        Excel::create($date, function($excel) use($export_goods){
            $excel->sheet('Leen', function($sheet) use($export_goods){

                $sheet->prependRow(1, array(
                    'ID', '货号', '出库数量', '名称', '价格', '库存', '类型'
                ));

                $sheet->setWidth(array(
                    'A'     =>  10,
                    'B'     =>  15,
                    'C'     =>  15,
                    'D'     =>  50,
                    'E'     =>  10,
                    'F'     =>  10,
                    'G'     =>  15
                ));
                foreach ($export_goods as $key=>$good) {

                    $type = '一般商品';
                    switch ($good['type']) {
                        case '0':
                            $type = '一般商品';
                            break;
                        case '1':
                            $type = 'e贸易';
                            break;
                    }

                    $sheet->row($key+2, array(
                            $good['goods_id'].' ', $good['goods_sn'].' ', $good['out_going_number'].' ', $good['goods_name'], $good['shop_price'].' ', $good['goods_number'].' ', $type
                    ));
                    $rows = $key + 2;
                    $sheet->cells("A1:H1", function($sheet) {
                        // $sheet->setBackground('#ADD8E6');       //设置背景
                        $sheet->setAlignment('left');           //设置水平对齐
                        $sheet->setValignment('middle');        //设置垂直居中

                        $sheet->setFont(array(
                            'family'     => '宋体',
                            'size'       => '12',
                            'bold'       =>  true
                        ));
                    });

                    $sheet->cells("A$rows:H$rows", function($sheet) {
                        // $sheet->setBackground('#ADD8E6');       //设置背景
                        $sheet->setAlignment('left');           //设置水平对齐
                        $sheet->setValignment('middle');        //设置垂直居中

                        $sheet->setFont(array(
                            'family'     => '宋体',
                            'size'       => '12'
                        ));
                    });
                }

            });
        })->export('xls');

        return Response()->json($return);
    }


    /**
     * 根据商品id数组获取商品信息
     * @param  [type] $goods_ids [商品id数组]
     * @return [type]            [description]
     */
    public function getGoodsByIds(Request $request, GoodsService $goodsService)
    {

        $goods_ids = $request->goods_ids;

        if (empty($goods_ids) || count($goods_ids)<1) {

            // throw new Exception("商品id数组不能为空");
            return 'fail';
        }

        return Response()->json($goodsService->getGoodsByIds($goods_ids)->toArray());
    }

}//end calss GoodsController
